<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        v-model="firm.name"
        clearable
        placeholder="请输入内容"
        class="search-main"
        @change="onChange"
        @input="onChange"
      />
      <el-button type="primary" @click="onQuerying">查询</el-button>
    </div>
    <div class="create-container">
      <el-button size="mini" type="primary" @click="$router.push('/companyAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="firmList">
        <el-table-column type="index" label="序号" :index="getIndex" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="mini" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/companyAdd/${row.id}`)">编辑</el-button>
            <el-button size="mini" type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="firm.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加合同 -->
    <el-dialog title="添加合同" :visible="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" style="width: 100%;" placeholder="请选择">
              <el-option v-for="item in rentBuildings" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              style="width: 100%;"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              v-model="rentForm.contractId"
              action="#"
              :http-request="uploadHandle"
              :before-upload="beforeUpload"
              :file-list="contractList"
            >
              <el-button v-if="!rentForm.contractId" size="small" type="primary" plain>上传合同文件</el-button>
              <el-button v-else size="small" type="success" plain disabled>已上传</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="onRentSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addcontractApi, delFirmApi, getFirmListApi, getRentBuildListApi, uploadApi } from '@/api/firm'

export default {
  data() {
    return {
      firmList: [],
      firm: {
        name: '',
        page: 1,
        pageSize: 5
      },
      total: 0,
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentBuildings: [],
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      contractList: [],
      firmId: ''
    }
  },
  created() {
    this.getFirmList()
  },
  methods: {
    async getFirmList() {
      const { rows, total } = await getFirmListApi(this.firm)
      this.firmList = rows
      this.total = total
    },
    getIndex(index) {
      return (this.firm.page - 1) * this.firm.pageSize + index + 1
    },
    handleCurrentChange(newPage) {
      this.firm.page = newPage
      this.getFirmList()
    },
    onQuerying() {
      this.firm.page = 1
      this.getFirmList()
    },
    onChange() {
      setTimeout(() => {
        this.firm.page = 1
        this.getFirmList()
      }, 500)
    },
    del(id) {
      this.$confirm('是否确认删除当前企业?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delFirmApi(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getFirmList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开
    async addRent(id) {
      const res = await getRentBuildListApi()
      this.firmId = id
      this.rentBuildings = res
      this.rentDialogVisible = true
    },
    // 关闭
    closeDialog() {
      this.contractList = []
      this.$refs.addForm.resetFields()
      this.rentDialogVisible = false
    },
    // 上传前验证
    beforeUpload(file) {
      const allowImgType = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同文件只能是 .doc, .pdf 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同文件大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 上传合同
    async uploadHandle(fileData) {
      // 1. 处理FormData
      const { file } = fileData
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')
      // 2. 上传并赋值
      const res = await uploadApi(formData)
      const { id, url } = res
      this.rentForm.contractId = id
      this.rentForm.contractUrl = url
      // 单独校验表单
      this.$refs.addForm.validateField('contractId')
    },
    async onRentSubmit() {
      const { buildingId, contractId, contractUrl, type, rentTime } = this.rentForm
      const startTime = rentTime[0]
      const endTime = rentTime[1]
      const targetData = new Date(startTime)
      console.log(new Date(), targetData)

      await addcontractApi({ enterpriseId: this.firmId, contractId, contractUrl, type, startTime, endTime, buildingId })
      this.$message.success('添加成功')
      this.contractList = []
      this.$refs.addForm.resetFields()
      this.rentDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
